package cloud.demarcia.rabbitregister.service.impl;

import cloud.demarcia.rabbitregister.constant.RedisConstant;
import cloud.demarcia.rabbitregister.entity.MemberEntity;
import cloud.demarcia.rabbitregister.exception.RabbitForgetException;
import cloud.demarcia.rabbitregister.repository.MemberRepository;
import cloud.demarcia.rabbitregister.service.ForgetService;
import cloud.demarcia.rabbitregister.service.MailService;
import cloud.demarcia.rabbitregister.util.PasswordEncipher;
import cloud.demarcia.rabbitregister.util.RandomCodeManager;
import cloud.demarcia.rabbitregister.vo.UserForgetVo;
import cloud.demarcia.rabbitregister.vo.UserRegisterVo;
import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Bojun Wen, wen_bj@outlook.com
 * @date 2022.02.26
 */
@Service
@Slf4j
public class ForgetServiceImpl implements ForgetService {
    @Resource
    private MailService mailService;
    @Resource
    private MemberRepository repository;
    @Resource
    private RandomCodeManager randomCodeManager;
    @Resource
    private PasswordEncipher passwordEncipher;
    @Override
    public void sendConfirmEmail(String email) {
        if(!Validator.isEmail(email)) throw new RabbitForgetException("邮件地址格式错误，请检查后提交");
        checkIfEmailExists(email);
        String code = randomCodeManager.getCode(email, RedisConstant.FORGET_EMAIL_PREFIX);
        mailService.sendForgetCodeMail(email,code);
    }

    @Override
    public void forget(UserForgetVo vo) {
        if(!Validator.isEmail(vo.getEmail())) throw new RabbitForgetException("邮件地址格式错误，请检查后提交");
        randomCodeManager.matchCode(vo.getEmail(), vo.getCode(),RedisConstant.FORGET_EMAIL_PREFIX);
        MemberEntity entity = repository.findByEmail(vo.getEmail());
        entity.setPassword(passwordEncipher.encode(vo.getPassword()));
        repository.save(entity);
        mailService.sendForgetSuccessMail(vo.getEmail());
    }


    private void checkIfEmailExists(String email){
        int count = repository.countByEmail(email);
        if(count!=1) throw new RabbitForgetException("该邮件地址尚未注册，请先注册Rabbit账号");
    }
}
